<?php

require_once('data/SugarBean.php');
require_once('modules/Tasks/Task.php');
require_once('include/utils.php');
require_once('include/TimeDate.php');
require_once('modules/edanz_Editor/edanz_Editor.php');

class TaskCreateTasks {
	function TaskCreateTasks(&$bean, $event, $arguments){
		global $mod_strings;
		global $app_list_strings;
		if($bean->status == 'Completed' &&  $bean->fetched_row['status'] != $bean->status){
			$related_editor_id = $bean->related_editor_id;
			$user = new User();
			switch ($bean->type){
				case 'CreateWikiAccountAndSendFishTest':
					$newTaskType = 'FishTestReceived';
					$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
					break;
				case 'FishTestReceived':
					$valid_doc_type = 'FishTest';
						$newTaskType = 'ReviewFishTest';
						$editor_candidate = new edanz_Editor();
						$editor_candidate->retrieve($related_editor_id);
						$assigned_user_id = ( $editor_candidate->assigned_user_id != "") ? $editor_candidate->assigned_user_id : NULL;
						$business_days_until_due = 4;
						$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id, NULL, $business_days_until_due);
					break;
				case 'ReviewFishTest':
					$valid_doc_type = 'FishTest';
						$editor_candidate = new edanz_Editor();
						$editor_candidate->retrieve($related_editor_id);
						switch ($editor_candidate->fish_test){
							case 'NotDone':
								$this->handleErrorRedirect($mod_strings['ERR_FISH_TEST_OUTCOME']);
								break;
							case 'Failed':
								$newTaskType = 'DeactivateWikiAccount';
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								break;
							case 'Borderline':
								$newTaskType = 'SecondTestReceived';
								$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								break;
							case 'Passed':
								$newTaskType = 'MiniCV';
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								$newTaskType = 'ContactDetails';
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								$newTaskType = 'ContractedFreelanceEditorAgreement';
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								$newTaskType = 'ConfidentialityAgreement';
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								$newTaskType = 'BankDetails';
								$assigned_user_id = $user->retrieve_user_id('editor_banking');
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);
								break;
						}
					break;
				case 'SecondTestReceived':
					$valid_doc_type = '2ndRecruitmentTest';
						$newTaskType = 'Review2ndTest';
						$editor_candidate = new edanz_Editor();
						$editor_candidate->retrieve($related_editor_id);
						$assigned_user_id = ( $editor_candidate->assigned_user_id != "") ? $editor_candidate->assigned_user_id : NULL;
						$business_days_until_due = 4;
						$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id, NULL, $business_days_until_due);
					break;
				case 'Review2ndTest':
					$valid_doc_type = '2ndRecruitmentTest';
						$editor_candidate = new edanz_Editor();
						$editor_candidate->retrieve($related_editor_id);
						switch ($editor_candidate->fish_test){
							case 'NotDone':
							case 'Borderline':
								$this->handleErrorRedirect($mod_strings['ERR_FISH_TEST_OUTCOME']);
								break;
							case 'Failed':
								$newTaskType = 'DeactivateWikiAccount';
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								break;
							case 'Passed':
								$newTaskType = 'MiniCV';
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								$newTaskType = 'ContactDetails';
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								$newTaskType = 'ContractedFreelanceEditorAgreement';
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								$newTaskType = 'ConfidentialityAgreement';
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								$newTaskType = 'BankDetails';
								$assigned_user_id = $user->retrieve_user_id('editor_banking');
								$this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);
								break;
						}
					break;
				case 'ContractedFreelanceEditorAgreement':
					break;
				case 'ConfidentialityAgreement':
					$valid_doc_type = 'ConfidentialityAgreement';
						$newTaskType = 'SetupCallWithCandidate';
						$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
					break;
				case 'CreateSugarAccount':
					$newTaskType = 'SetupCallWithCandidate';
					$this->createNewRecruitmentTask($newTaskType, $related_editor_id);
					break;
				case 'SetupCallWithCandidate':
					break;
				case 'MiniCV':
					$valid_doc_type = 'MiniCV';
						$assigned_user_id = $user->retrieve_user_id('cv_editing');
						$newTaskType = 'EditEditorCV';
						$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);
					break;
				case 'EditEditorCV':
					$valid_doc_type = 'MiniCV';
						$assigned_user_id = $user->retrieve_user_id('cv_quality');
						$newTaskType = 'QCEditorCV';
						$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);

					break;
				case 'QCEditorCV':
					$valid_doc_type = 'MiniCV';
						require_once('modules/edanz_Editor/edanz_Editor.php');
						$related_editor = new edanz_Editor();
						$related_editor->retrieve($related_editor_id);
						$tasks = $related_editor->get_linked_beans('tasks','Task');
						foreach($tasks as $task) {
								$newTaskType = 'UploadCVToJapanGlobalWebsite';
								$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id);
								break;
						}
					break;
				case 'UploadCVToJapanGlobalWebsite':
					$assigned_user_id = $user->retrieve_user_id('chinese_translation');
					$newTaskType = 'ChineseCVTranslation';
					$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);
					$assigned_user_id = $user->retrieve_user_id('japanese_translation');
					$newTaskType = 'JapaneseCVTranslation';
					$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);

                                        $assigned_user_id = $user->retrieve_user_id('cv_reviewing');
                                        $newTaskType = 'MiniCVpostpublicationreview';
                                        $newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);

					break;
				case 'UploadEnglishMiniCVToChinaWebsite':
					$assigned_user_id = $user->retrieve_user_id('chinese_translation');
					$newTaskType = 'SendMiniCVToChineseTranslationVendor';
					$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);
					break;


				case 'UpdateEditorMiniCV':
					$assigned_user_id = $user->retrieve_user_id('cv_quality');
					$newTaskType = 'QCupdatedEditorMiniCV';
					$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);
					break;

				case 'QCupdatedEditorMiniCV':
					$assigned_user_id = $user->retrieve_user_id('japanese_translation');
					$newTaskType = 'UploadEnglishandJapaneseMiniCV';
					$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);
					
					$assigned_user_id = $user->retrieve_user_id('chinese_translation');
					$newTaskType = 'UploadChineseMiniCV';
					$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);
					break;

				case 'SendMiniCVToChineseTranslationVendor':
					$assigned_user_id = $user->retrieve_user_id('chinese_translation');
					$newTaskType = 'ChineseCVTranslation';
					$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);
					break;
				case 'ChineseCVTranslation':
					break;
				case 'SendCVToJapaneseTranslationVendor':
					$assigned_user_id = $user->retrieve_user_id('japanese_translation');
					$newTaskType = 'JapaneseCVTranslation';
					$newTask = $this->createNewRecruitmentTask($newTaskType, $related_editor_id, $assigned_user_id);
					break;
				case 'JapaneseCVTranslation':
					break;
				case 'InternalQualityReview':
					if($this->validFeedbackCount($bean) > 0 || empty($_REQUEST)){ //If the $_REQUEST is empty, then this must be a SOAP call, so no validation
						require_once('modules/edanz_Editor/edanz_Editor.php');
                                                $reviewer = new edanz_Editor();
                                                $reviewer->retrieve($bean->assigned_user_id);
						if($reviewer->isOnProbation()){
							$newTaskType = 'QualityAudit';
							$newTask = new Task();
							$newTask->name = $app_list_strings['task_type_dom'][$newTaskType]." - ".$reviewer->name;
							$newTask->date_due = $bean->date_due;
							$newTask->status = 'Not Started';
							$newTask->type = $newTaskType;
							$user = new User();
							$newTask->assigned_user_id = $user->retrieve_user_id('quality_control');
							$newTask->related_editor_id = $bean->related_editor_id;
							$newTask->origin_system = $bean->origin_system;
							$newTask->origin_module = $bean->origin_module;
							$newTask->origin_id = $bean->origin_id;
							$newTask->workload = $bean->workload;
							$newTask->deliverable_id = $bean->deliverable_id;
							$newTask->save();
						}

						break;
					}else{
						$this->handleErrorRedirect($mod_strings['ERR_NO_VALID_FEEDBACK']);
					}
					break;
			}
		}
	}

	function createNewRecruitmentTask($type, $related_editor_id, $assigned_user_id = NULL, $related_editor_name = NULL, $business_days_until_due = NULL,$status = 'Not Started')
	{
		global $app_list_strings;
		$dateStart = gmdate($GLOBALS['timedate']->get_db_date_time_format());
		$dateDue = is_null($business_days_until_due) ? NULL : $this->add_business_days($dateStart, $business_days_until_due);
		$user = new User();
		if(is_null($assigned_user_id)){
			$assigned_user_id = $user->retrieve_user_id('recruitment_administrator');
		}
		if(is_null($related_editor_name)){
			$user->retrieve($related_editor_id);
			$related_editor_name = $user->full_name;
		}
		$newTask = new Task();
		$newTask->name = $app_list_strings['task_type_dom'][$type]." - ".$related_editor_name;
		//$newTask->date_start = $dateStart;
		$newTask->date_due = $dateDue;
		$newTask->status = $status;
		$newTask->priority = 'Medium';
		$newTask->type = $type;
		$newTask->assigned_user_id = $assigned_user_id;
		$newTask->related_editor_id = $related_editor_id;
		$newTask->description = $app_list_strings['task_type_descriptions'][$type];
            if($status == 'Pending Input')
		$newTask->save(false);
            else
		$newTask->save(true);
		return $newTask;
	}
	
	function transferRelatedDocuments($oldTask, $newTask){
		$oldTask->load_relationship('documents');
		$documents = $oldTask->documents->get();
		$newTask->load_relationship('documents');
		foreach($documents as $document_id){
			$newTask->documents->add($document_id);
		}
	}
	
	function handleErrorRedirect($message){
		header("Location: index.php?module=Tasks&action=Error&error_string=".urlencode($message));
		exit;
	}
	
	function validRevisionCount($task, $valid_doc_type=null){
		require_once('modules/Documents/Document.php');
		require_once('modules/DocumentRevisions/DocumentRevision.php');
		$task->load_relationship('documents');
                $documents = $task->documents->get();
		$doc = new Document();
		$doc_revision = new DocumentRevision();
		$valid_revision_count = 0;
		foreach($documents as $document_id){
			$doc->retrieve($document_id);
			$doc_revision->retrieve($doc->document_revision_id);
			if((is_null($valid_doc_type) || $doc->template_type == $valid_doc_type) && $doc_revision->task_type == $task->type){
				$valid_revision_count++;
			}
		}
		return $valid_revision_count;
	}

        function validFeedbackCount($task){
		require_once('modules/edanz_Deliverables/edanz_Deliverables.php');
		$deliverable = new edanz_Deliverables();
		$deliverable->retrieve($task->deliverable_id);
		$feedback_items = $deliverable->get_linked_beans('feedback', 'edanz_Feedback');
		return count($feedback_items);
	}

	function add_business_days($startdate,$buisnessdays){

		$i=0;
		$dayx = strtotime($startdate);
  		while($i < $buisnessdays){
			$day = date('N',$dayx);
			$date = date('Y-m-d H:i:s',$dayx);
			if($day < 6)
				$i++;
			$dayx = strtotime($date.' +1 day');
		}
		$startdate = date('Y-m-d H:i:s',$dayx);
		$date = new DateTime($startdate);
		$timezone = new DateTimeZone('Asia/Tokyo');
		$date->setTimezone( $timezone );
		//$date->modify("+{$buisnessdays} weekdays");
                $due_date = new DateTime($date->format('Y-m-d'), $timezone);
                $due_date->setTimezone(new DateTimeZone('UTC'));
		return $due_date->format($GLOBALS['timedate']->get_db_date_time_format());

	}
}

?>
